package com.lz.library.extension

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager

/**
 *  author: you : 2022/11/19
 */

/**
 * 获取StaggeredGridLayoutManager最后一项位置
 */
fun StaggeredGridLayoutManager.getLastPosition() : Int {
    val lastPositions = findLastVisibleItemPositions(IntArray(spanCount))
    var maxPosition = -1
    lastPositions?.forEach { if (it > maxPosition) maxPosition = it }
    return maxPosition
}

fun RecyclerView.isRecyclerViewScrolledLast(): Boolean = isRecyclerViewScrolledLast(1)

fun RecyclerView.isRecyclerViewScrolledLast(listFooterSize: Int): Boolean {
    if (layoutManager != null) {
        val lm: RecyclerView.LayoutManager = layoutManager!!
        val loadLastPosition = lm.itemCount - listFooterSize - 1
        if (loadLastPosition >= 0) {
            if (lm is LinearLayoutManager) {
                return lm.findLastVisibleItemPosition() >= loadLastPosition
            } else if (lm is StaggeredGridLayoutManager) {
                return maxPosition(lm.findLastVisibleItemPositions(IntArray(2))) >= loadLastPosition
            }
        }
    }
    return false
}

/**
 * 最大的即为最后一个位置
 * @param positions
 * @return
 */
fun maxPosition(positions: IntArray?): Int {
    var maxPosition = -1
    positions?.forEach { if (it > maxPosition) maxPosition = it }
    return maxPosition
}

/**
 * 最小值
 * @param positions
 * @return
 */
fun minPosition(positions: IntArray?): Int {
    var minPosition = Int.MAX_VALUE
    positions?.forEach { if (it < minPosition) minPosition = it}
    return minPosition
}